import socketserver
import threading


class ChatHandler(socketserver.BaseRequestHandler):
    clients = {}

    def setup(self):
        super().setup()
        self.event = threading.Event()
        self.lock = threading.Lock()
        with self.lock:
            self.clients[self.client_address] = self.request

    def handle(self):
        super().handle()
        while not self.event.is_set():
            data = self.request.recv(1024)
            if not data or data == b'quit':
                with self.lock:
                    self.clients.pop(self.client_address)
                    print(2, self.clients)
                    break
            with self.lock:
                for c in self.clients.values():
                    c.send(data + b'++++++++++')
            print(1, self.clients)

    def finish(self):
        super().finish()
        self.event.set()


class CtatServer:
    def __init__(self, handler, ip='127.0.0.1', port=60001):
        self.handler = handler
        self.adr = ip, port

    def start(self):
        self.server = socketserver.ThreadingTCPServer(('127.0.0.1', 60001), ChatHandler)
        threading.Thread(target=self.server.serve_forever, name='server', daemon=True).start()

    def stop(self):
        self.server.server_close()


if __name__ == '__main__':
    cs = CtatServer(ChatHandler)
    cs.start()
    while True:
        m = input(">>>")
        if m == 'quit':
            cs.stop()
            break

# 做的不错